package com.dogdog.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.protocol.ResponseConnControl;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.radar.RadarNearbyResult;
import com.baidu.mapapi.radar.RadarNearbySearchOption;
import com.baidu.mapapi.radar.RadarSearchError;
import com.baidu.mapapi.radar.RadarSearchListener;
import com.baidu.mapapi.radar.RadarSearchManager;
import com.baidu.mapapi.radar.RadarUploadInfo;
import com.baidu.mapapi.radar.RadarUploadInfoCallback;
import com.baidu.mapapi.utils.DistanceUtil;
import com.dogdog.activity.R;
import com.dogdog.bean.Location;
import com.dogdog.bean.LocationListInfo;
import com.dogdog.bean.LoginDataBean;
import com.dogdog.bean.MarkerInfo;
import com.dogdog.bean.MarkerListInfo;
import com.dogdog.bean.Me;
import com.dogdog.bean.RoundUserInfo;
import com.dogdog.bean.Status;
import com.dogdog.bean.UserId;
import com.dogdog.manager.C;
import com.dogdog.manager.MyApplication;
import com.dogdog.manager.MyOrientationListener;
import com.dogdog.manager.MyOrientationListener.OnOrientationListener;
import com.dogdog.util.LocationUtil;
import com.google.gson.Gson;

import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Hand_found_location extends Fragment {
	private View tab1;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private Marker marker;
	private Context context;
	private List<Location> userlocation;
	List<MarkerInfo> infoList;
	private Location location;
	private Me userData = MyApplication.getMeData();
	int user_id = userData.getID();
	private Gson gson;
	// String userid=String.valueOf(user_id);
	// 工具类
	private LocationUtil locationUtil;
	// 定位相关
	private LocationClient mLocationClient;
	private MyRadarSearchListener mRadarSearchListener;
	private boolean isFirstIn = true;
	public double mLatitude;
	public double mLongtitude;
	// 自定义定位图标
	private BitmapDescriptor mIconLocation;
	private MyOrientationListener myOrientationListener;
	private float mCurrentX;
	private LocationMode mLocationMode;
	private LatLng pt = null;
	private LatLng pt2 = null;
	private int pageIndex = 0;
	// 覆盖物相关
	private BitmapDescriptor mMarker;
	List<RoundUserInfo> distanceList;
	public static List<String> idList;

	// private RelativeLayout mMarkerLy;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 初始化定位
		SDKInitializer.initialize(getActivity().getApplicationContext());
		tab1 = inflater.inflate(R.layout.fragment_found_location, container,
				false);
		this.context = getActivity();
		initView();
		initLocation();
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {

			@Override
			public void run() {
				drawMarker();

			}
		};
		timer.schedule(task, 1500);
		return tab1;
	}

	private void initLocation() {
		mLocationMode = LocationMode.NORMAL;// 设置定位模式
		mLocationClient = new LocationClient(getActivity());
		locationUtil = new LocationUtil(getActivity());
		mRadarSearchListener = new MyRadarSearchListener();
		mLocationClient.registerLocationListener(mRadarSearchListener);
		LocationClientOption option = new LocationClientOption();
		// 设置返回的定位结果坐标系
		option.setCoorType("bd09ll");
		// 可选，设置是否需要地址信息，默认不需要
		option.setIsNeedAddress(true);
		// 是否打开GPS
		option.setOpenGps(true);
		// option.setScanSpan(1000);
		mLocationClient.setLocOption(option);
		// 初始化图标
		mIconLocation = BitmapDescriptorFactory
				.fromResource(R.drawable.navi_map_gps_locked);
		myOrientationListener = new MyOrientationListener(context);
		myOrientationListener
				.setOnOrientationListener(new OnOrientationListener() {
					@Override
					public void onOrientationChanged(float x) {
						mCurrentX = x;
					}
				});

	}

	private void initView() {
		mMapView = (MapView) tab1.findViewById(R.id.id_bmapView);
		mBaiduMap = mMapView.getMap();
		// mBaiduMap.clear();
		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
		// 设置地图范围
		mBaiduMap.setMapStatus(msu);
		mBaiduMap
				.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

					@Override
					public boolean onMarkerClick(Marker arg0) {

						int uid = arg0.getExtraInfo().getInt("id");
						final String id = String.valueOf(uid);
						StringRequest markerInfo = new StringRequest(
								Method.POST, C.URL.MarkerInfo,
								new Response.Listener<String>() {

									@Override
									public void onResponse(String response) {
										gson = new Gson();
										Status s = gson.fromJson(
												response.toString(),
												Status.class);
										if (s.getState() == 1) {
											Toast.makeText(context,
													"获取markerinfo成功",
													Toast.LENGTH_SHORT).show();
											MarkerListInfo markerListInfo = gson
													.fromJson(
															response,
															MarkerListInfo.class);
											String userEmail = markerListInfo
													.getResult()
													.getUser_email();
											String userName = markerListInfo
													.getResult().getUser_name();
											InfoWindow infoWindow;
											// 动态生成一个Button对象，用户在地图中显示InfoWindow
											final Button textInfo = new Button(
													getActivity());
											textInfo.setBackgroundResource(R.drawable.whilebutton_bg);
											textInfo.setPadding(10, 10, 10, 10);
											textInfo.setTextColor(Color.BLACK);
											textInfo.setTextSize(12);
											textInfo.setText("用户名:" + userName
													+ "\n邮箱:" + userEmail);
											// 得到点击的覆盖物的经纬度
											LatLng ll = marker.getPosition();
											// 将marker所在的经纬度的信息转化成屏幕上的坐标
											Point p = mBaiduMap.getProjection()
													.toScreenLocation(ll);
											p.y -= 90;
											LatLng llInfo = mBaiduMap
													.getProjection()
													.fromScreenLocation(p);
											// 初始化infoWindow，最后那个参数表示显示的位置相对于覆盖物的竖直偏移量，这里也可以传入一个监听器
											infoWindow = new InfoWindow(
													textInfo, llInfo, 0);
											mBaiduMap
													.showInfoWindow(infoWindow);// 显示此infoWindow
											// 让地图以备点击的覆盖物为中心
											MapStatusUpdate status = MapStatusUpdateFactory
													.newLatLng(ll);
											mBaiduMap.setMapStatus(status);

										}

									}
								}, new Response.ErrorListener() {

									@Override
									public void onErrorResponse(
											VolleyError error) {
										// TODO Auto-generated method stub
										Toast.makeText(context,
												"获取markerinfo失败",
												Toast.LENGTH_SHORT).show();
									}
								}) {
							@Override
							protected Map<String, String> getParams()
									throws AuthFailureError {
								Map<String, String> param = new HashMap<String, String>();
								param.put("id", id);
								return param;
							}
						};
						MyApplication.getHttpQueue().add(markerInfo);

						return true;
					}
				});
	}

	private class MyRadarSearchListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation arg0) {
			// TODO Auto-generated method stub
			MyLocationData data = new MyLocationData.Builder()//
					.direction(mCurrentX)//
					.accuracy(arg0.getRadius())//
					.latitude(arg0.getLatitude())//
					.longitude(arg0.getLongitude())//
					.build();
			mBaiduMap.setMyLocationData(data);
			// 设置自定义图标
			MyLocationConfiguration config = new MyLocationConfiguration(
					mLocationMode, true, mIconLocation);
			mBaiduMap.setMyLocationConfigeration(config);
			// 更新经纬度
			mLatitude = arg0.getLatitude();
			mLongtitude = arg0.getLongitude();
			Log.e("tag", "经度" + mLatitude + "   纬度" + mLongtitude);
			pt = new LatLng(mLatitude, mLongtitude);

			if (isFirstIn) {
				LatLng latLng = new LatLng(arg0.getLatitude(),
						arg0.getLongitude());
				MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
				mBaiduMap.animateMapStatus(msu);
				isFirstIn = false;
			}
			locationUtil.saveLocation(user_id, mLatitude, mLongtitude);
			mLocationClient.stop();

		}

	}

	/**
	 * 得到数据库保存的用户坐标，在地图上相应位置表上覆盖物
	 */
	public void drawMarker() {
		StringRequest markerInfo = new StringRequest(Method.POST,
				C.URL.LocationList, new Response.Listener<String>() {

					@Override
					public void onResponse(String response) {

						distanceList = new ArrayList<RoundUserInfo>();
						idList = new ArrayList<String>();
						gson = new Gson();
						Status s = gson.fromJson(response.toString(),
								Status.class);
						if (s.getState() == 1) {
							LocationListInfo locationListInfo = gson.fromJson(
									response, LocationListInfo.class);				
							LatLng pt3 = new LatLng(mLatitude, mLongtitude);
							for (int i = 0; i <= locationListInfo.getResult()
									.size() - 1; i++) {
								double mLatitude2 = locationListInfo
										.getResult().get(i).getLatitude();
								double mLongtitude2 = locationListInfo
										.getResult().get(i).getLongtitude();
								pt2 = new LatLng(mLatitude2, mLongtitude2);
								if (pt2 == null) {
									Toast.makeText(getActivity(), "未获取到位置",
											Toast.LENGTH_LONG).show();
									break;
								}
								BitmapDescriptor bitmap = BitmapDescriptorFactory
										.fromResource(R.drawable.maker);
								MarkerOptions option = new MarkerOptions()
										.icon(bitmap).position(pt2);
								marker = (Marker) mBaiduMap.addOverlay(option);
								if (user_id == locationListInfo.getResult()
										.get(i).getUser_id()) {
									marker.remove();
								}
								Bundle bundle = new Bundle();
								bundle.putInt("id", locationListInfo
										.getResult().get(i).getId());
								marker.setExtraInfo(bundle);
								DistanceUtil du = new DistanceUtil();
								double distance = du.getDistance(pt3, pt2);
								RoundUserInfo info = new RoundUserInfo();
								// UserId userId=new UserId();
								info.setDistance(String.valueOf(distance).substring(0, 3));
								// userId.setUser_id(locationListInfo.getResult().get(i).getUser_id());
								Log.e("起点坐标：", mLatitude + ":::" + mLongtitude);
								Log.e("终点坐标：", mLatitude2 + ":::"
										+ mLongtitude2);
								Log.e("distance", String.valueOf(distance).substring(0, 3) + "");		
//								GetDistance(mLatitude, mLongtitude, mLatitude2,
//										mLongtitude2);
								idList.add(locationListInfo.getResult().get(i)
										.getUser_id().toString());
								distanceList.add(info);
							}

						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(context, "获取信息失败", Toast.LENGTH_SHORT)
								.show();
					}
				});
		MyApplication.getHttpQueue().add(markerInfo);
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// 开启定位
		mBaiduMap.setMyLocationEnabled(true);
		mLocationClient.start();
		// 开启方向传感器
		myOrientationListener.start();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		mLocationClient.start();
		mBaiduMap.setMyLocationEnabled(true);
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mMapView.onResume();
	}

	@Override
	public void onPause() {

		mLocationClient.stop();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mMapView.onPause();
		super.onPause();

	}

	@Override
	public void onStop() {
		super.onStop();

		// 停止定位
		mBaiduMap.setMyLocationEnabled(false);
		mLocationClient.stop();
		// 停止方向传感器
		myOrientationListener.stop();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mMapView.onDestroy();
	}

//	private double EARTH_RADIUS = 6378.137;
//
//	private double rad(double d) {
//		return d * Math.PI / 180.0;
//	}
//
//	public double GetDistance(double lat1, double lng1, double lat2, double lng2) {
//		double radLat1 = rad(lat1);
//		double radLat2 = rad(lat2);
//		double a = radLat1 - radLat2;
//		double b = rad(lng1) - rad(lng2);
//		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
//				+ Math.cos(radLat1) * Math.cos(radLat2)
//				* Math.pow(Math.sin(b / 2), 2)));
//		s = s * EARTH_RADIUS;
//		s = Math.round(s * 10000) / 10000;
//		Log.e("距离s", s + "");
//		return s;
//	}

}
